<template>
  <div class="timeline-view">
    <div v-if="loading" class="loading-container">
      <el-skeleton animated :rows="5" />
    </div>

    <div v-else-if="rooms.length === 0" class="empty-container">
      <el-empty description="暂无会议室数据" />
    </div>

    <div v-else class="timeline-container">
      <!-- 时间轴头部 -->
      <div class="timeline-header">
        <div class="room-column">
          <div class="column-title">会议室</div>
        </div>
        <div class="time-columns">
          <div v-for="hour in workHours" :key="hour" class="time-column" :class="{ 'current-hour': isCurrentHour(hour) }">
            {{ hour }}:00
          </div>
        </div>
      </div>

      <!-- 时间轴内容 -->
      <div class="timeline-content">
        <div
          v-for="room in rooms"
          :key="room.id"
          class="timeline-row"
          :class="{ 'selected-room': selectedRoomId === room.id }"
          @click="handleRoomSelect(room)"
        >
          <div class="room-column">
            <div class="room-info">
              <div class="room-name">{{ room.roomName }}</div>
              <div class="room-tags">
                <el-tag v-if="isRoomInUse(room)" effect="plain" size="small" type="danger">使用中</el-tag>
                <el-tag v-if="room.isApproval === '1'" effect="plain" size="small" type="warning">需审批</el-tag>
              </div>
              <div class="room-meta">
                <span class="room-position">{{ room.positionDescription || '无位置信息' }}</span>
                <span class="room-capacity">
                  <el-icon><user /></el-icon>
                  {{ room.capacity || '--' }}
                </span>
              </div>
            </div>
          </div>

          <div class="time-columns timeline-background">
            <!-- 背景网格线 -->
            <div
              v-for="hour in workHours"
              :key="`grid-${hour}`"
              class="grid-line"
              :class="{ 'current-hour-line': isCurrentHour(hour) }"
            ></div>

            <!-- 活动块 -->
            <div
              v-for="(activity, index) in room.activityInfos"
              :key="`activity-${room.id}-${index}`"
              class="activity-block"
              :style="getActivityStyle(activity)"
              :title="`${activity.title}: ${formatTimeRange(activity.startTime, activity.endTime)}`"
              @click.stop="handleActivityClick(activity)"
            >
              <div class="activity-content">
                <div class="activity-title">{{ activity.title }}</div>
                <div class="activity-time">{{ formatTimeRange(activity.startTime, activity.endTime) }}</div>
              </div>
            </div>

            <!-- 当前时间线 -->
            <div v-if="isToday && showCurrentTime" class="current-time-line" :style="getCurrentTimePosition()"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { User } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { computed, ref } from 'vue'
import type { ActivityInfo, MeetingRoom } from '/@/types/api'

// 定义会议活动类型
interface ActivityInfo {
  id: string
  title: string
  startTime: string
  endTime: string
  userName?: string
  userDept?: string
  [key: string]: any
}

// 定义会议室类型
interface ConferenceRoom {
  id: string | number
  roomName: string
  capacity?: string | number
  positionDescription?: string
  equipment?: string
  isApproval?: string
  activityInfos?: ActivityInfo[]
  [key: string]: any
}

// 组件属性
const props = defineProps<{
  rooms: MeetingRoom[]
  loading: boolean
  currentDate: string
  selectedRoomId: number | null
}>()

// 组件事件
const emit = defineEmits<{
  (e: 'roomSelect', room: MeetingRoom): void
  (e: 'activityClick', activity: ActivityInfo): void
}>()

// 工作时间范围（9点到18点）
const workHours = Array.from({ length: 10 }, (_, i) => i + 9)

// 是否显示当前时间线
const showCurrentTime = ref(true)

// 是否为当天
const isToday = computed(() => {
  return props.currentDate === dayjs().format('YYYY-MM-DD')
})

// 格式化时间范围
const formatTimeRange = (startTime: string, endTime: string) => {
  return `${startTime.substr(11, 5)} - ${endTime.substr(11, 5)}`
}

// 检查会议室是否在使用中
const isRoomInUse = (room: MeetingRoom) => {
  if (!room.activityInfos || room.activityInfos.length === 0) {
    return false
  }

  const now = new Date()

  // 如果不是今天，永远返回非使用中
  if (!isToday.value) {
    return false
  }

  return room.activityInfos.some((activity) => {
    const startTime = new Date(`${props.currentDate} ${activity.startTime.substr(11, 5)}`)
    const endTime = new Date(`${props.currentDate} ${activity.endTime.substr(11, 5)}`)
    return startTime <= now && now <= endTime
  })
}

// 检查是否为当前小时
const isCurrentHour = (hour: number) => {
  if (!isToday.value) return false
  const currentHour = new Date().getHours()
  return currentHour === hour
}

// 获取会议活动在时间轴上的样式
const getActivityStyle = (activity: ActivityInfo) => {
  // 工作时间是 9:00-18:00，总共 9 小时
  const workStart = 9
  const workEnd = 18
  const totalHours = workEnd - workStart

  // 活动开始和结束时间
  const startHour = parseInt(activity.startTime.substr(11, 2))
  const startMinute = parseInt(activity.startTime.substr(14, 2))
  const endHour = parseInt(activity.endTime.substr(11, 2))
  const endMinute = parseInt(activity.endTime.substr(14, 2))

  // 相对于工作开始时间的小时数
  const relativeStart = Math.max(0, startHour + startMinute / 60 - workStart)
  const relativeEnd = Math.min(totalHours, endHour + endMinute / 60 - workStart)

  // 计算宽度百分比和左侧位置百分比
  const leftPercent = (relativeStart / totalHours) * 100
  const widthPercent = ((relativeEnd - relativeStart) / totalHours) * 100

  return {
    left: `${leftPercent}%`,
    width: `${widthPercent}%`,
  }
}

// 获取当前时间在时间轴上的位置
const getCurrentTimePosition = () => {
  const now = new Date()
  const currentHour = now.getHours()
  const currentMinute = now.getMinutes()

  // 工作时间范围
  const workStart = 9
  const workEnd = 18
  const totalHours = workEnd - workStart

  // 如果当前时间不在工作时间范围内，不显示
  if (currentHour < workStart || currentHour >= workEnd) {
    return { display: 'none' }
  }

  // 计算当前时间相对于工作开始时间的位置百分比
  const relativeTime = currentHour + currentMinute / 60 - workStart
  const leftPercent = (relativeTime / totalHours) * 100

  return {
    left: `${leftPercent}%`,
  }
}

// 处理选择会议室
const handleRoomSelect = (room: MeetingRoom) => {
  emit('roomSelect', room)
}

// 处理点击活动块
const handleActivityClick = (activity: ActivityInfo) => {
  emit('activityClick', activity)
}
</script>

<style scoped>
.timeline-view {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 16px;
  overflow: auto;
}

.loading-container,
.empty-container {
  padding: 40px 0;
  text-align: center;
}

.timeline-container {
  width: 100%;
  overflow-x: auto;
}

.timeline-header {
  display: flex;
  border-bottom: 1px solid #ebeef5;
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 2;
}

.column-title {
  padding: 12px;
  font-weight: 500;
  color: #303133;
}

.room-column {
  width: 200px;
  min-width: 200px;
  border-right: 1px solid #ebeef5;
}

.time-columns {
  display: flex;
  flex: 1;
  position: relative;
}

.time-column {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  font-size: 13px;
  color: #606266;
  border-right: 1px dashed #ebeef5;
}

.time-column:last-child {
  border-right: none;
}

.time-column.current-hour {
  color: #409eff;
  font-weight: bold;
}

.timeline-content {
  position: relative;
}

.timeline-row {
  display: flex;
  height: 80px;
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.3s;
  cursor: pointer;
}

.timeline-row:hover {
  background-color: #f5f7fa;
}

.timeline-row.selected-room {
  background-color: #ecf5ff;
  border: 1px solid #409eff;
}

.room-info {
  padding: 12px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.room-name {
  font-weight: 500;
  margin-bottom: 4px;
  color: #303133;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.room-tags {
  display: flex;
  gap: 5px;
  margin-bottom: 5px;
}

.room-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.room-position {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.room-capacity {
  display: flex;
  align-items: center;
  gap: 4px;
}

.timeline-background {
  position: relative;
  height: 100%;
}

.grid-line {
  position: absolute;
  height: 100%;
  width: 1px;
  background-color: #ebeef5;
  top: 0;
}

.grid-line:nth-child(1) {
  left: 10%;
}
.grid-line:nth-child(2) {
  left: 20%;
}
.grid-line:nth-child(3) {
  left: 30%;
}
.grid-line:nth-child(4) {
  left: 40%;
}
.grid-line:nth-child(5) {
  left: 50%;
}
.grid-line:nth-child(6) {
  left: 60%;
}
.grid-line:nth-child(7) {
  left: 70%;
}
.grid-line:nth-child(8) {
  left: 80%;
}
.grid-line:nth-child(9) {
  left: 90%;
}

.current-hour-line {
  background-color: rgba(64, 158, 255, 0.2);
  width: 10%;
}

.activity-block {
  position: absolute;
  height: 60%;
  top: 20%;
  background-color: #e6a23c;
  border-radius: 4px;
  z-index: 1;
  overflow: hidden;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition:
    transform 0.2s,
    box-shadow 0.2s;
}

.activity-block:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  z-index: 2;
}

.activity-content {
  padding: 4px 8px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.activity-title {
  font-size: 12px;
  color: #fff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
}

.activity-time {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.9);
}

.current-time-line {
  position: absolute;
  height: 100%;
  width: 2px;
  background-color: #f56c6c;
  top: 0;
  z-index: 3;
}

@media screen and (max-width: 768px) {
  .room-column {
    width: 150px;
    min-width: 150px;
  }

  .timeline-row {
    height: 70px;
  }

  .room-info {
    padding: 8px;
  }
}
</style>
